<template>
  <div>
    <el-form ref="form"
             :model="news"
             label-width="80px"
             :rules="formRules"
             label-position="left"
    >
      <el-form-item label="标题" prop="title">
        <el-input v-model="news.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <el-input type="textarea" v-model="news.content" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item label="作者" prop="author">
        <el-input type="text" v-model="news.author" placeholder="请输入作者"></el-input>
      </el-form-item>
      <el-form-item label="创建时间" prop="createDate">
        <el-date-picker v-model="news.createDate"
                        type="date"
                        placeholder="请选择日期"
                        value-format="yyyy-MM-dd"
        ></el-date-picker>
      </el-form-item>
      <el-form-item align="left">
        <el-button type="primary" @click="addNews">添加</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  export default {
    name: "addNews",
    data(){
      return {
        news:{},
        formRules:{//表单校验规则
          title:[//username项的校验规则，每一项规则可以有多个要求
            {required:true,message:"标题不能为空",trigger:"blur"}
          ],
          content:[//password项的校验规则
            {required:true,message:"内容不能为空",trigger:"blur"}
          ],
          author:[//password项的校验规则
            {required:true,message:"作者不能为空",trigger:"blur"}
          ],
          createDate:[//password项的校验规则
            {required:true,message:"时间不能为空",trigger:"blur"}
          ]
        }
      }
    },
    methods:{
      addNews(){
        //通过this.$refs[”表单的ref“]获取表单
        this.$refs["form"].validate((valid)=>{
          //valid表示表单校验的结果 true|false
          if(valid){
            this.axios({
              url:"/news",
              method:"POST",
              data:this.news
            }).then((resp)=>{
              alert("添加成功！");
              this.news={};
            });
          }
          return valid;
        })
      }
    }
  }
</script>

<style scoped>

</style>
